<template>
  <div>
    <el-dialog
      :title="title"
      v-model="state.isShow"
      lock-scroll
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
      align-center
      width="600px"
      @closed="closed"
    >
      <ul>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[120px] pl-2 flex item justify-end">
            <span>活动状态</span>
            <span class="mt-[-1px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px]">
            <el-radio-group v-model="form.Status">
              <el-radio :value="1" size="large">开启</el-radio>
              <el-radio :value="0" size="large">关闭</el-radio>
            </el-radio-group>
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[120px] pl-2 flex item justify-end">
            <span>排序</span>
            <span class="mt-[-1px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px]">
            <el-input-number
              v-model="form.Sort"
              class="!w-[246px]"
              :min="0"
              controls-position="right"
            />
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[120px] pl-2 flex items-center justify-end">
            <span>活动广告图片</span>
            <el-tooltip effect="dark" content="建议尺寸：710*260" placement="top-start">
              <el-icon class="text-primary !text-[16px]"><Warning /></el-icon>
            </el-tooltip>
            <span class="mt-[-3px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px] overflow-hidden">
            <BannerPreview
              @delete="form.ActivityImg = ''"
              v-if="form.ActivityImg"
              :src="form.ActivityImg"
            />
            <div v-else class="w-[100px] h-[100px]" v-loading="state.aloading">
              <el-upload
                ref="uploadRef"
                drag
                action="#"
                accept="image/jpeg,image/png,image/jpg"
                :show-file-list="false"
                :multiple="false"
                :limit="1"
                :http-request="(e: any) => UploadImage(e, 1)"
                :before-upload="beforePicUpload"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[120px] pl-2 flex items-center justify-end">
            <span>活动内容图片</span>
            <el-tooltip effect="dark" content="建议尺寸：710" placement="top-start">
              <el-icon class="text-primary !text-[16px]"><Warning /></el-icon>
            </el-tooltip>
            <span class="mt-[-3px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px] overflow-hidden">
            <BannerPreview
              @delete="form.ContentImg = ''"
              v-if="form.ContentImg"
              :src="form.ContentImg"
            />
            <div v-else class="w-[100px] h-[100px]" v-loading="state.cloading">
              <el-upload
                ref="uploadRef"
                drag
                action="#"
                accept="image/jpeg,image/png,image/jpg"
                :show-file-list="false"
                :multiple="false"
                :limit="1"
                :http-request="(e: any) => UploadImage(e, 2)"
                :before-upload="beforePicUpload"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[120px] pl-2 flex items-center justify-end">
            <span>跳转地址</span>
            <el-tooltip
              effect="dark"
              content="活动内容图片和跳转地址都有设置时，仅跳转地址生效。"
              placement="top-start"
            >
              <el-icon class="text-primary !text-[16px]"><Warning /></el-icon>
            </el-tooltip>
            <span class="mt-[-3px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px]">
            <el-input class="!w-[400px]" v-model="form.ActivityUrl" />
          </div>
        </li>
      </ul>
      <template #footer>
        <el-button @click="closed">取 消</el-button>
        <el-button
          :disabled="state.updating"
          :loading="state.updating"
          type="primary"
          @click="handleSubmit"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import BannerPreview from "@/components/banner-preview.vue";
import { reqUploadImg } from "@/api/user";
import { message } from "@/utils/message";
import { reqActivityDiscountAdd, reqActivityDiscountEdit } from "@/api/activity";

const props = withDefaults(
  defineProps<{
    type?: "edit" | "add";
    data: ActivityDiscountMo | null;
  }>(),
  {
    type: "add",
    data: null
  }
);
const emit = defineEmits(["update"]);
const uploadRef = ref();
const title = computed(() => (props.type == "edit" ? "编辑优化活动" : "新增优惠活动"));
const state = reactive({
  isShow: false,
  aloading: false,
  cloading: false,
  updating: false
});
const defaultForm = {
  Status: 0,
  Sort: 1,
  ActivityImg: "",
  ContentImg: "",
  ActivityUrl: ""
};

const form = reactive({ ...defaultForm });
const closed = () => {
  state.isShow = false;
};
const open = () => {
  if (props.type == "add") {
    Object.assign(form, defaultForm);
  } else {
    Object.assign(form, props.data);
  }
  state.isShow = true;
};

const UploadImage = async (e: any, type = 1) => {
  try {
    if (type == 1) {
      state.aloading = true;
    } else {
      state.cloading = true;
    }
    let params = new FormData();
    params.append("ImgPath", e.file);
    let res = await reqUploadImg(params);
    state.aloading = false;
    state.cloading = false;
    if (type == 1) {
      form.ActivityImg = "/" + res.data.ImgPath;
    } else {
      form.ContentImg = "/" + res.data.ImgPath;
    }
    uploadRef.value?.clearFiles();
  } catch (error) {
    state.aloading = false;
    state.cloading = false;
    uploadRef.value?.clearFiles();
    console.log(error);
  }
};

const beforePicUpload = (file: any) => {
  const isIMAGE = file.type === "image/jpeg" || "image/jpg" || "image/png";
  const isLt200K = file.size / 1024 < 200;

  if (!isIMAGE) {
    message.warning("上传文件只能是图片格式!");
  }
  if (!isLt200K) {
    message.warning("上传头像图片大小不能超过 200KB!");
  }
  return isIMAGE && isLt200K;
};

const handleSubmit = async () => {
  if (!form.Sort && form.Sort != 0) {
    message.warning("请输入排序");
    return;
  }
  if (!form.ActivityImg) {
    message.warning("请上传活动图片");
    return;
  }
  if (!form.ActivityUrl) {
    message.warning("请输入活动地址");
    return;
  }
  state.updating = true;
  try {
    if (props.type == "add") {
      await reqActivityDiscountAdd({
        Status: Number(form.Status),
        Sort: Number(form.Sort),
        ActivityImg: form.ActivityImg,
        ContentImg: form.ContentImg,
        ActivityUrl: form.ActivityUrl
      });
    } else {
      await reqActivityDiscountEdit({
        Id: props.data?.Id,
        Status: Number(form.Status),
        Sort: Number(form.Sort),
        ActivityImg: form.ActivityImg,
        ContentImg: form.ContentImg,
        ActivityUrl: form.ActivityUrl
      });
    }
    message.success(props.type == "add" ? "添加活动成功" : "修改活动成功");
    state.updating = false;
    emit("update");
    setTimeout(() => {
      closed();
    }, 200);
  } catch (error) {
    state.updating = false;
    console.log(error);
  }
};
defineExpose({
  open
});
</script>
<style scoped lang="scss">
:deep() {
  .el-dialog__body {
    padding: 20px;
  }
  .el-input-number .el-input__inner {
    text-align: left !important;
  }
  .el-radio {
    margin-right: 10px !important;
  }
}
</style>
